import React, { Component, PropTypes } from 'react';
import Echarts from 'echarts';
import { connect } from 'dva'
import {
  Input,
  Button,
  Select,
  Form,
  Modal,
  Row,
  Col,
  Icon,
  message,
} from 'antd';
import Style from './home.less';
import NumberPlay from '../../util/numberPlay';
import $ from 'jquery';
import Service from "../../service";
const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
import mapopacity from "../../../img/mapopacity.png"
import mapstarticon from "../../../img/gjstarticpn.png"

var map;
let pointArr = [];
let pointMarkArr = [];
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      uAdressData: {}
    };
  }
  componentDidMount() {
    let self = this;

    // this.props.queryStatistics({ token: token });
    self.props.getWechatConfig({
      params: {
        url: Service.baseHost + '/'
      },
      func: function (result) {
        if (result) {
          window.wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: result.appId, // 必填，公众号的唯一标识
            timestamp: result.timestamp, // 必填，生成签名的时间戳
            nonceStr: result.nonceStr, // 必填，生成签名的随机串
            signature: result.signature,// 必填，签名
            jsApiList: ['getLocation', 'uploadImage'] // 必填，需要使用的JS接口列表
          });

          window.wx.ready(function () {
            // console.log('成功')

            self.getLocationInit();
            self.state.timer = setInterval(() => {
              self.getLocationInit('refresh');
            }, 10000)
            // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
          });
          window.wx.error(function (res) {
            // console.log(res)
            // console.log('失败')
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
          });
        }

      }
    })
    self.initMap(119.691521, 29.790466);

    //  self.getLocationInit();
  }
  getLocationInit = (type) => {
    let self = this;
    window.wx.getLocation({
      dataType: 'jsonp',
      type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function (res) {
        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
        // message.success('获取1：latitude:' + latitude + "longitude=" + longitude)

        // var speed = res.speed; // 速度，以米/每秒计
        // var accuracy = res.accuracy; // 位置精度
        // message.success('latitude:'+latitude+"longitude="+longitude)
        let gpsPoint = new BMap.Point(longitude, latitude);
        // let mk = BMap.Convertor.translate(gpsPoint, 0, translateCallback);
        setTimeout(function () {
          BMap.Convertor.translate(gpsPoint, 0, function (points) {
            let baiduPoint = points;
            pointMarkArr.push(baiduPoint)
            // pointArr.push(longitude,latitude)
            // message.success('转换1：latitude:' + points.lat + "longitude=" + points.lng)
            pointArr.push({ lat: points.lat, log: points.lng });
            if (!type) {
              self.initMap(points.lng, points.lat);
            }
            self.markerMapMy(points.lng, points.lat);
            var circle = new BMap.Circle(points, 1000, { fillColor: "#000", strokeWeight: 1, fillOpacity: 0.3, strokeOpacity: 0.3, enableEditing: true });
            map.addOverlay(circle);

            //         let latitude='30.25725';
            // let longitude='120.20523';
            // let gpsPoint = new BMap.Point(longitude, latitude);
            // let points=gpsPoint;
            // pointMarkArr.push(gpsPoint)
            // pointArr.push({ lat: points.lat, log: points.lng });
            // if(!type){
            //   self.initMap(points.lng, points.lat);
            // }


            // var circle = new BMap.Circle(points,1000,{fillColor:"#000", strokeWeight: 1 ,fillOpacity: 0.3, strokeOpacity: 0.3,enableEditing:true});
            // map.addOverlay(circle);

            // self.markerMapMy(points.lng, points.lat);


            // self.markerMapMy(points.lng, points.lat);
            // 车辆信息
            self.getBikeInfo(type);



          }); //真实经纬度转成百度坐标
        }, 2000)
      },
      fail: function () {
        // message.error('失败')
        console.log('失败111')
      }
    });
    // let latitude='29.793554';
    // let longitude='119.563277';
    // let gpsPoint = new BMap.Point(longitude, latitude);
    // let points=gpsPoint;
    // pointMarkArr.push(gpsPoint)
    // pointArr.push({ lat: points.lat, log: points.lng });
    // self.initMap(points.lng, points.lat);

    // var circle = new BMap.Circle(points,1000,{fillColor:"#000", strokeWeight: 1 ,fillOpacity: 0.3, strokeOpacity: 0.3,enableEditing:true});
    // map.addOverlay(circle);

    // self.markerMapMy(points.lng, points.lat);
    // self.getBikeInfo();
  }
  getBikeInfo = (type) => {
    let self = this;
    const token = localStorage.getItem('token');
    self.props.e_bikeInfo({
      params: {
        token: token,
      },
      func: function (result) {
        if (result) {
          self.setState({
            kData: result
          })
          // 有车辆信息的时候去定位
          if (result.location) {
            let long = result.location.split(',');
            pointMarkArr[1] = new BMap.Point(long[0], long[1]);
            pointArr[1] = { lat: long[1], log: long[0] };
            self.markerMapK(long[0], long[1], '车辆位置');

            if (!type) {
              map.setViewport(pointMarkArr);
            }
          }
        }


      }
    })
  }
  // 地图初始化
  initMap = (longitude, latitude) => {
    let self = this;
    map = new BMap.Map("mapWrap", { enableMapClick: false });  //创建地图
    var point = new BMap.Point(longitude, latitude);
    map.centerAndZoom(point, 15);
    map.enableScrollWheelZoom();//启动鼠标滚轮缩放地图
    map.enableKeyboard();//启动键盘操作地图
  }
  markerMapMy = (longitude, latitude) => {
    let self = this;
    var maker = self.addMarkerMy(new window.BMap.Point(longitude, latitude));
  }
  addMarkerMy = (point) => {
    // 姓名_头像_车牌号_车架号
    const token = localStorage.getItem('token');

    // var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png",
    var myIcon = new BMap.Icon(mapstarticon,
      new BMap.Size(50, 50), {
        anchor: new BMap.Size(0, 0),//这句表示图片相对于所加的点的位置
        imageOffset: new BMap.Size(0, 0)

      });

    // var myIcon = new BMap.Icon("https://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
    //     offset: new BMap.Size(10, 25), // 指定定位位置  
    //     imageOffset: new BMap.Size(0, 0 - 12 * 25) // 设置图片偏移  
    // });
    var marker = new BMap.Marker(point, { icon: myIcon });
    this.addInfoWindow(marker, '我的位置');
    map.addOverlay(marker);
    return marker;
  }
  addInfoWindow = (marker, desc, type) => {
    // console.log(poi)
    // type存在的时候就显示快递员
    let self = this;
    let entity_desc = desc;
    let text;
    // let entity_desc = poi.entity_desc.split('_');
    // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
    if (type) {
      text = '<div class="mapwrapk"><div class="mapwrap mapwrap1"><span>' + entity_desc + '</span></div><div class="mapwrapLebal"><span>车辆位置</span></div></div>';
    } else {
      text = '<div class="mapwrapLebal"><span>' + entity_desc + '</span></div>';

    }

    var label = new window.BMap.Label(text, { offset: new window.BMap.Size(20, -10) });
    marker.setLabel(label);
    var clo = "";
    var info = new window.BMap.InfoWindow("<p>" + entity_desc + "</p>"); // 创建信息窗口对象

    // map.setViewport(points);
  }
  markerMapK = (longitude, latitude, realname) => {
    let self = this;
    var maker = self.addMarkerK(new window.BMap.Point(longitude, latitude), realname);
  }
  addMarkerK = (point, realname) => {
    // console.log(point)
    // 姓名_头像_车牌号_车架号
    const token = localStorage.getItem('token');

    // var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png",
    var myIcon = new BMap.Icon(mapopacity,
      new BMap.Size(-38, 55), {
        // anchor: new BMap.Size(22, 51),//这句表示图片相对于所加的点的位置
        imageOffset: new BMap.Size(0, 0)

      }
    );

    // var myIcon = new BMap.Icon("https://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
    //     offset: new BMap.Size(10, 25), // 指定定位位置  
    //     imageOffset: new BMap.Size(0, 0 - 12 * 25) // 设置图片偏移  
    // });

    var marker = new BMap.Marker(point, { icon: myIcon });
    this.addInfoWindow(marker, realname, 'k');

    map.addOverlay(marker);
    return marker;
  }
  componentWillUnmount() {
    if (this.state.timer != null) {
      clearInterval(this.state.timer);

    }
  }

  editFun = () => {
    this.context.router.push(`/1/app/kmyedit`);
  }
  lasturlFun = () => {
    this.context.router.push(`/1/app/kindex`);
  }
  carlocationurlFun = () => {
    this.context.router.push(`/1/app/carlocation`);
  }
  homeurlFun = () => {
    this.context.router.push(`/1/app/kmy`);
  }
  openFun = () => {
    let self = this;
    let token = localStorage.getItem('token');
    let v = self.state.selectVal;
    if (!v) {
      message.error('请选择电动车');
    }
    self.setState({
      loading: 'block'
    })
    self.props.update({
      params: {
        devices_id: v,
        status: 'open',
        token: token
      },
      func: function (data) {
        if (data) {
          self.state.timerNum = 0;
          self.state.timer = setInterval(() => {
            self.state.timerNum++;
            if (self.state.timerNum >= 8) {
              self.setState({
                loading: 'none'
              })
              clearInterval(self.state.timer);
            }
            self.receiveFun(data.data, 1);
          }, 4000)

        }
      }
    })

  }
  receiveFun = (uuid, type) => {
    let self = this;
    let token = localStorage.getItem('token');
    let params = { 'uuid': uuid, 'token': token };
    $.ajax({
      url: `${Service.baseUrl}/devices/receive`,   //列表
      type: 'POST',
      data: params,
      success: function (data) {
        if (data.code == 200) {
          if (self.state.timer != null) {
            clearInterval(self.state.timer);
          }
          self.setState({
            loading: 'none'
          })
          if (data.data.status == 1) {
            if (type == 1) {
              message.success('开启成功!', 1.5);
            } else {
              message.success('关闭成功!', 1.5);
            }
          } else {
            if (type == 1) {
              message.error('开启失败!', 1.5);
            } else {
              message.error('关闭失败!', 1.5);
            }
          }

        } else {
          if (self.state.timerNum >= 8) {
            message.error(data.error, 1.5);
          }
        }
      }.bind(this),
      error: function (xhr, status, err) { }.bind(this)
    })
  }
  closeFun = () => {
    let self = this;
    let token = localStorage.getItem('token');
    let v = self.state.selectVal;
    if (!v) {
      message.error('请选择电动车');
    }
    self.setState({
      loading: 'block'
    })
    self.props.update({
      params: {
        devices_id: v,
        status: 'close',
        token: token
      },
      func: function (data) {
        if (data) {
          self.state.timerNum = 0;
          self.state.timer = setInterval(() => {
            self.state.timerNum++;
            if (self.state.timerNum >= 6) {
              self.setState({
                loading: 'none'
              })
              clearInterval(self.state.timer);
            }
            self.receiveFun(data.data, 2);
          }, 5000)

        }
      }
    })
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { data } = this.props;
    let vehicleData = data || [];
    // console.log(data);
    // console.log(this.props);
    return (
      <div className={Style.wrap}>
        <div className={Style.headWrap}>
          <div className={Style.navTitle}>
            车辆位置
          </div>
        </div>

        <div className={Style.conWrap}>
          <div className={Style.mapWrap} id="mapWrap">

          </div>

        </div>
        <div className={Style.foot}>
          <Row type="flex">
            <Col span={8} order={1} onClick={this.lasturlFun}>
              <Icon style={{ fontSize: 20 }} type="heart" theme="outlined" /><p>最后一公里</p>
            </Col>
            <Col span={8} order={2} className={Style.on} onClick={this.carlocationurlFun}>
              <Icon style={{ fontSize: 20 }} type="environment" theme="outlined" /><p>车辆位置</p>
            </Col>
            <Col span={8} order={2} onClick={this.homeurlFun}>
              <Icon style={{ fontSize: 20 }} type="user" theme="outlined" /><p>我的</p>
            </Col>
          </Row>
        </div>
        <div className={Style.marsk} style={{ display: this.state.loading }}>
          <Icon type="loading" className={Style.loading} />
          <p className={Style.loadText}>请耐心等待...</p>
        </div>
      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  // console.log(state)
  return {
    data: state.vehicle.data,
    loading: !!state.loading.global
  }
}

function dispatchToProps(dispatch) {
  return {
    queryStatistics(payload, params) {
      dispatch({ type: 'vehicle/list', payload })
    },
    update(payload, params) {
      dispatch({ type: 'vehicle/update', payload })
    },
    receive(payload, params) {
      dispatch({ type: 'vehicle/receive', payload })
    },
    e_bikeInfo(payload, params) {
      dispatch({
        type: 'kmodel/e_bikeInfo',
        payload
      })
    },
    getWechatConfig(payload, params) {
      dispatch({
        type: 'umodel/getWechatConfig',
        payload
      })
    }
  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
